package org.javamap;

import java.awt.Image;
import java.awt.Toolkit;

import java.io.File;

import java.util.HashMap;
import java.util.Iterator;

/**
  * Handles mapping of files to Hex images.
  */
public abstract class ImageManager
{
	/**
	  * Not instantiable.
	  */
	private ImageManager() { }
	
	/**
	  * Loads an image with the given filename from the image path.
	  * @param imageKey  only used for error messages.
	  */
	public static Image createImage(String fname, String imageKey)
	{
		Image im;
		File fid = new File(IMAGE_PATH+fname);
		if (!fid.exists()) {
			System.err.println("WARNING: image \""+imageKey
					+"\" => \""+IMAGE_PATH+fname+"\" not found.");
			im = ERROR_IMAGE;
		} else
			im = Toolkit.getDefaultToolkit().createImage(IMAGE_PATH+fname);
			
		return im;
	}
	
	public static Image createImage(String fname)
	{ return createImage(fname, "?"); }
	
	/**
	  * Must return a non-null image for the given key.
	  */
	public static Image retrieveImage(String imageKey)
	{
		Image im = (Image) cachedImages.get(imageKey);
		if (im == null) { // might not be loaded yet
			String fname = (String) imageFiles.get(imageKey);
			im = createImage(fname, imageKey);
			cachedImages.put(imageKey, im);
		}
		
		return im;
	}
	
	public static void addImage(String imageKey, String fname)
	{
		cachedImages.remove(imageKey);
		imageFiles.put(imageKey, fname);
		storeImageMap();
	}
	
	public static void removeImage(String imageKey)
	{
		cachedImages.remove(imageKey);
		imageFiles.remove(imageKey);
		storeImageMap();
	}
	
	/**
	  * Iterate over the keys in this manager.
	  */
	public static Iterator iterateKeys() 
	{ return imageFiles.keySet().iterator(); }
	
//*************************  Private Methods  *******************************//
	private static void storeImageMap()
	{
		try {
			java.io.FileOutputStream fos = new java.io.FileOutputStream(
					IMAGE_PATH+"ImageMap.dat");
			java.io.ObjectOutputStream oos 
					= new java.io.ObjectOutputStream(fos);
			oos.writeObject(imageFiles);
		} catch (Exception e) { e.printStackTrace(); }
	}
	
	private final static String IMAGE_PATH = "../images/";
	private final static HashMap imageFiles, cachedImages = new HashMap();
	private final static Image ERROR_IMAGE;
	
	static {
		HashMap tempMap = new HashMap();
		try {
		java.io.FileInputStream fis = new java.io.FileInputStream(
				IMAGE_PATH+"ImageMap.dat");
		java.io.ObjectInputStream ois = new java.io.ObjectInputStream(fis);
		tempMap = (HashMap) ois.readObject();
		} catch (Exception ioe) { ioe.printStackTrace(); }
		imageFiles = tempMap;
		
		java.io.File fid = new java.io.File(IMAGE_PATH+"error.gif");
		if (!fid.exists())
			System.err.println("FILE NOT FOUND!");
		ERROR_IMAGE = Toolkit.getDefaultToolkit().createImage(
				IMAGE_PATH+"error.gif");
	}	
}


